var express = require('express');
var path = require('path');
var logger = require('morgan');
var fs = require('fs');
var FileStreamRotator = require('file-stream-rotator');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var flash = require('connect-flash');  
// var hbs = require('hbs');
var template = require('art-template');


var index = require('./routes/index');
var users = require('./routes/users');
var publish = require('./routes/publish');

var app = express();

// view engine setup
app.engine('art', require('express-art-template'));
// app.set('view engine', 'hbs');
// require.extensions['.html'] = template.extension;
// template.config('extname', '.html');
// app.engine('.html', template.__express);
app.set('view engine', 'art');
app.set('views', path.join(__dirname, 'views'));
// 设置片段目录
// hbs.registerPartials(__dirname + '/views/partials');

// log  
var logDirectory = path.join(__dirname,'logs');
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);

// create a rotating write stream
var accessLogStream = FileStreamRotator.getStream({
  filename: logDirectory + '/access-%DATE%.log',
  frequency: 'daily',
  verbose: false
});
app.use(logger('combined', {stream: accessLogStream}));
// app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    secret: 'shop app', //secret的值建议使用随机字符串
    cookie: {maxAge: 60 * 1000 * 30} // 过期时间（毫秒）
    , resave: true, saveUninitialized: true
}));

app.use(flash());
//设置flash  
// app.use(function(req, res, next){  
//   res.locals.error = req.flash('error') || "";  
//   res.locals.success = req.flash('success') || "";  
//   next();  
// });  

app.use(function(req,res,next){
	res.locals.user=req.session.user;

	var err = req.flash('error');
	var success = req.flash('success');

	res.locals.error = err.length ? err : null;
	res.locals.success = success.length ? success : null;

	next();
});
app.use('/', index);
app.use('/users', users);
app.use('/publish', publish);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  console.log('1e');
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  console.log('[2e]');
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error.art');
});

module.exports = app;
